package com.zccx.eth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zccx.eth.dao.CzfInfoRepository;
import com.zccx.eth.model.CzfInfo;
import com.zccx.eth.service.ICzfInfoService;
import com.zccx.eth.util.DomainUtil;
import com.zccx.eth.util.object.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("czfInfoService ")
public class CzfInfoServiceImpl implements ICzfInfoService {
    @Autowired
    private CzfInfoRepository czfInfoRepository;
    @PersistenceContext
    private EntityManager manager;

    @Override
    public void saveInfo(CzfInfo info) {
        czfInfoRepository.save(info);
    }

    @Override
    public CzfInfo searchInfo(String bano, String zpf) {
        String sql = "select * from czf_info where 1=1 ";
        if(StringUtils.isNotEmpty(zpf)){
            sql += " and zpf='" + zpf + "'";
        }
        if(StringUtils.isNotEmpty(bano)){
            sql += " and bano='" + bano + "'";
        }
        Query query = manager.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, Object>> resultList = query.getResultList();

        List<CzfInfo> list = new ArrayList<>();
        resultList.forEach(r -> list.add(new JSONObject(r).toJavaObject(CzfInfo.class)));
        if(list.size() >= 1){
            return list.get(0);
        }
        return null;
    }

    @Override
    public Page<CzfInfo> getList(int pageNum, int pageSize,String search) {
        return czfInfoRepository.findAll(new Specification<CzfInfo>() {
            @Override
            public Predicate toPredicate(Root<CzfInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                if(StringUtils.isNotEmpty(search)){
                    criteriaQuery.where(criteriaBuilder.like(root.get("bano"),"%" + DomainUtil.escapeSpecialChar(search) + "%"));
                }
                return null;
            }
        },new PageRequest(pageNum - 1, pageSize,new Sort(Sort.Direction.DESC, "id")));
    }

    @Override
    public CzfInfo getOne(int id) {
        return czfInfoRepository.findOne(id);
    }

    @Override
    public void delInfo(int id) {
        czfInfoRepository.delete(id);
    }
}
